<template>
  <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="formRules"
      size="small"
      :inline="false"
      label-width="100px"
    >
      <el-form-item label="主题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入主题"
          maxlength="32"
          size="small"
        />
      </el-form-item>
      <el-form-item label="候选人" prop="candidateId">
        <el-select
          v-model="formData.candidateId"
          placeholder="请选择候选人"
          size="small"
          filterable
        >
          <el-option
            v-for="item in candidateList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="candidateName">
        <el-input
          v-model="formData.candidateName"
          placeholder="请输入候选人姓名"
          maxlength="64"
          size="small"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="candidatePhone">
        <el-input
          v-model="formData.candidatePhone"
          placeholder="请输入候选人手机号"
          maxlength="16"
          size="small"
        />
      </el-form-item>
      <el-form-item label="入职职位" prop="oaPositionId">
        <el-select
          v-model="selectedPosition"
          placeholder="请选择入职职位"
          size="small"
          value-key="id"
          filterable
          @change="positionChange"
        >
          <el-option
            v-for="item in positionList"
            :key="item.id"
            :label="item.name"
            :value="item"
          />
        </el-select>
        <span style="margin: 0 20px">职级：{{ formData.gradeName || "-" }}</span>
        <span>职等：{{ formData.gradeLevel || "-" }}</span>
      </el-form-item>
      <el-form-item label="入职部门" prop="oaDeptId">
        <el-tree-select
          v-model="formData.oaDeptId"
          node-key="id"
          value-key="id"
          :props="{ value: 'id', label: 'name' }"
          :data="deptList"
          check-strictly
          :render-after-expand="false"
          filterable
          size="small"
        />
      </el-form-item>
      <el-form-item label="直属上级" prop="directSuperiorId">
        <el-select
          v-model="formData.directSuperiorId"
          placeholder="请选择直属上级"
          size="small"
          filterable
        >
          <el-option
            v-for="item in staffList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工作性质" prop="staffType">
        <el-select v-model="formData.staffType" placeholder="请选择工作性质" size="small">
          <el-option
            v-for="item in dictMap['StaffType']"
            :key="item.value"
            :value="item.value"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="候选人状态" prop="staffState">
        <el-select
          v-model="formData.staffState"
          placeholder="请选择候选人状态"
          size="small"
        >
          <el-option
            v-for="item in candidateStateList"
            :key="item.value"
            :value="item.value"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同期限" prop="contractTerm">
        <el-input-number
          v-model="formData.contractTerm"
          :min="1"
          :max="999"
          :controls="false"
        />
        <el-radio-group v-model="formData.contractTermType" style="margin-left: 15px">
          <el-radio label="0" size="small">天</el-radio>
          <el-radio label="1" size="small">月</el-radio>
          <el-radio label="2" size="small">年</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="试用期" prop="trialTerm">
        <el-select v-model="formData.trialTerm" placeholder="请选择试用期" clearable>
          <el-option
            v-for="item in dictMap['StaffTrialLimit']"
            :key="item.value"
            :value="item.value"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="试用期工资" prop="trialSalary">
        <el-input-number
          v-model="formData.trialSalary"
          :min="0"
          :max="99999999"
          :controls="false"
          size="small"
          style="margin-right: 10px"
        />元
      </el-form-item>
      <el-form-item label="工资" prop="salary">
        <el-input-number
          v-model="formData.salary"
          :min="0"
          :max="99999999"
          :controls="false"
          size="small"
        />
        <span style="margin: 0 20px 0 5px">元</span>
        <el-select
          v-model="formData.salaryType"
          placeholder="请选择工资的类型"
          size="small"
        >
          <el-option
            v-for="item in dictMap['OfferSalaryTimeType']"
            :key="item.value"
            :value="item.value"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <!--    <el-form-item label="工资类型" prop="salaryType">-->
      <!--      <el-select v-model="formData.salaryType" placeholder="请选择工资的类型" size="small">-->
      <!--        <el-option v-for="item in dictMap['OfferSalaryTimeType']" :key="item.value" :value="item.value" :label="item.name" />-->
      <!--      </el-select>-->
      <!--    </el-form-item>-->
      <el-form-item label="工作地点" prop="workAddress">
        <el-input
          v-model="formData.workAddress"
          placeholder="请填写工作地点"
          maxlength="128"
          size="small"
        />
      </el-form-item>
      <el-form-item label="入职地点" prop="entryAddress">
        <el-input
          v-model="formData.entryAddress"
          placeholder="请填写入职地点"
          maxlength="128"
          size="small"
        />
      </el-form-item>
      <el-form-item label="奖金/福利" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请填写奖金/福利描述"
          size="small"
        />
      </el-form-item>
      <el-form-item label="优先度">
        <el-radio-group v-model="formData.priority">
          <el-radio :label="0" size="small">普通</el-radio>
          <el-radio :label="1" size="small">高</el-radio>
        </el-radio-group>
      </el-form-item>
      <!--    <el-form-item label="通知时间" prop="remindState">-->
      <!--      <el-radio-group v-model="formData.remindState">-->
      <!--        <el-radio v-for="item in remindTimes" :key="item.value" :label="item.value" size="small">{{ item.label }}</el-radio>-->
      <!--      </el-radio-group>-->
      <!--    </el-form-item>-->
      <!--    <el-form-item label="通知方式" prop="remindType">-->
      <!--      <el-checkbox-group v-model="formData.remindType" size="small">-->
      <!--        <el-checkbox label="1">应用、公众号通知</el-checkbox>-->
      <!--        <el-checkbox label="2">短信通知</el-checkbox>-->
      <!--      </el-checkbox-group>-->
      <!--    </el-form-item>-->
    </el-form>
</template>

<script>
// 新建offer OA_NEW_OFFER
import {onMounted, reactive, toRefs,ref, watch, nextTick} from 'vue'
import {getStateList, getListByType} from '/@/api/oa/candidate'
import {getRemindTimes} from '/@/api/matter'
import {getDictByCodes} from '/@/api/sys/dict'
import {getPositionSelector} from '/@/api/oa/office/position'
import {getEnterpriseUsers} from '/@/api/sys/user'
import {getTreeList} from '/@/api/oa/dept'
import {getSelectorData} from '/@/api/oa/staff';
import { homeApi } from "/@/api/home/index";
import { format } from "/@/views/home/component/lib/utils";
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
    name: 'CreateOfferForm',
    props: {
        selectTime: {
            type: String,
            default: null
        },
        editId: {
          type: String,
          default: null
        }
    },
    setup(props, context) {
      const { editId, selectTime } = toRefs(props)
        const homeCalendar = homeApi();
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const ruleFormRef = ref({});
        const state = reactive({
            formData: {
                candidateId: null,
                title: '新建Offer',
                candidateName: null,  // 候选人姓名
                candidatePhone: null, // 候选人手机号
                oaPositionId: null,   // 入职职位id
                gradeName: null,    // 职级
                gradeLevel: null,   // 职等
                oaDeptId: null,   // 入职部门id
                directSuperiorId: null,   // 入职直属上级（员工）id
                staffType: '0',    // 工作性质
                staffState: '5',   // 员工状态
                contractTerm: null,   // 合同期限
                contractTermType: '2', // 合同期限的日期类型 0天 1月 2年
                trialTerm: null,    // 试用期 字典StaffTrialLimit
                trialSalary: null,    // 试用期工资
                salary: null,   // 工资
                salaryType: '0',   // 工资时间类型 0月薪 字典OfferSalaryTimeType
                workAddress: '',    // 工作地点
                entryAddress: '',   // 入职地点
                remark: null,     // 存放奖金&福利描述
                remindState: 'NONE',     // 提醒时间, 根据枚举类MatterRemindTimeEnum
                remindType: [],     // 提醒方式, 多选
                state: 0,           // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
                priority: 0        // 优先级 0普通 1重要
            },
            dictMap: {},
            candidateStateList: [],   // 候选人状态选择数据列表
            candidateList: [],
            remindTimes: [],
            deptList: [],   // 部门列表
            positionList: [],   // 职位数据列表
            enterpriseUserList: [],   // 企业用户数据列表
            staffList: [],    // 员工列表
            selectedPosition: null,  // 选中的职位 内有级联职等、职级
            originForm: {}
        })
        const formRules = reactive({
            candidateId: {required: true, message: '请选择候选人', trigger: 'change'},
            title: {required: true, message: '请填写主题', trigger: 'blur'},
            candidateName: {required: true, message: '请填写候选人名称', trigger: 'blur'},
            candidatePhone: {required: true, message: '请填写候选人手机号', trigger: 'blur'},
            oaPositionId: {required: true, message: '请选择入职职位', trigger: 'change'},
            oaDeptId: {required: true, message: '请选择入职部门', trigger: 'change'},
            directSuperiorId: {required: true, message: '请选择直属上级', trigger: 'change'},
            staffType: {required: true, message: '请选择工作性质', trigger: 'change'},
            staffState: {required: true, message: '请选择候选人状态', trigger: 'change'},
            contractTerm: {required: true, message: '请选择合同期限', trigger: 'change'},
            trialTerm: {required: true, message: '请选择试用期', trigger: 'change'},
            trialSalary: {required: true, message: '请填写试用期工资', trigger: 'blur'},
            salary: {required: true, message: '请填写工资', trigger: 'blur'}
        });

        const getCandidateData = async () => {  // 获取面试通过的
            try {
                const res = await getListByType('4')
                state.candidateList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const getRemindData = async () => {   // 通知时间列表
            try {
                const res = await getRemindTimes()
                state.remindTimes = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const getCandidateStates = async() => {   // 候选人状态列表
            try {
                const res = await getStateList()
                state.candidateStateList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const getPositions = async() => {   // 职位列表
            try {
                const res = await getPositionSelector()
                state.positionList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const getEnterpriseUserList = async () => {   // 企业用户列表
            try {
                const res = await getEnterpriseUsers()
                state.enterpriseUserList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const getDeptList = async () => {   // OA的部门列表
            try {
                const res = await getTreeList()
                state.deptList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const getStaffList = async() => {
            try {
                const res = await getSelectorData()
                state.staffList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const positionChange = val => {
            state.formData.oaPositionId = val.id
            if (val.officeGrade) {
                state.formData.gradeName = val.officeGrade.name
                state.formData.gradeLevel = val.officeGrade.grade
            } else {
                state.formData.gradeName = state.formData.gradeLevel = null
            }
        }
        let close = () => {
            context.emit("BISHISTATUS");
            reset()
        };
        let submit = () => {
            if (!ruleFormRef) return;
            return new Promise(async (resolve, reject) => {
                await ruleFormRef.value.validate((valid, fields) => {
                    if (valid) {
                        console.log(state.formData);
                        if(editId.value) {
                          // 编辑
                          for(let key in state.formData){
                            if(state.originForm.hasOwnProperty(key)){
                              state.originForm[key] = state.formData[key]
                            }
                            if(state.originForm.info.hasOwnProperty(key)){
                              state.originForm.info[key] = state.formData[key]
                            }
                          }
                          storesCalendarConfig.setEventForm(state.originForm)
                          reset()
                          close()
                          resolve('edit') 
                        }else{
                          homeCalendar.addNewOffer(state.formData).then((res) => {
                            if (res.code === 0) {
                                reset()
                                close()
                                resolve()
                            }else{
                              reject()
                            }
                          });
                        }
                    } else {
                        reject()
                        console.log("error submit!", fields);
                    }
                });
            })
            
        };
        const reset = () => {
            if (!ruleFormRef) return
            ruleFormRef.value.resetFields()
        }
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
                if(data.remindType){
                  state.formData.remindType = data.remindType.split(',')
                }
              })
            }
          }        
        )
        onMounted(() => {
            try {
                getDictByCodes(['OfferSalaryTimeType', 'StaffType', 'StaffTrialLimit']).then(res => {
                state.dictMap = res.data
                })
            } catch (e) {
                console.log(e)
            }
            getDeptList()
            getStaffList()
            getPositions()
            getRemindData()
            getCandidateData()
            getCandidateStates()
            getEnterpriseUserList()
        })
        return {
            ...toRefs(state),
            getDeptList,
            getStaffList,
            getPositions,
            getRemindData,
            positionChange,
            getCandidateData,
            getCandidateStates,
            getEnterpriseUserList,
            submit,
            close,
            formRules,
            ruleFormRef,
            reset
        }
    }
}
</script>

<style>

</style>